package org.sfgeeq.chapter2.helper;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.sfgeeq.chapter2.util.PropsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

/**
 * 数据库操作类
 * Created by Administrator on 2016/5/16.
 */
public class DatabaseHelper {
    //为了确保一个线程中只有一个Connection，我们可以使用ThreadLocal来存入本地线程变量，也就是说将当前线程中的Connection放到ThrealdLocal中存起来，这些Connection一定不会出现线程不安全的问题。可以将它理解为一个隔离线程的容器
    private static final ThreadLocal<Connection> CONNECTION_HOLDER=new ThreadLocal<Connection>();

    private static final QueryRunner QUERY_RUNNER;

    private static final BasicDataSource DATA_SOURCE;

    private static final Logger log= LoggerFactory.getLogger(DatabaseHelper.class);


    /**
     * 读取配置文件
     */
    static {
        QUERY_RUNNER=new QueryRunner();
        Properties conf= PropsUtil.loadProps("config.properties");
        String DRIVER=conf.getProperty("jdbc.driver");
        String URL=conf.getProperty("jdbc.url");
        String USERNAME=conf.getProperty("jdbc.username");
        String PASSWORD=conf.getProperty("jdbc.password");
        DATA_SOURCE=new BasicDataSource();
        DATA_SOURCE.setDriverClassName(DRIVER);
        DATA_SOURCE.setUrl(URL);
        DATA_SOURCE.setUsername(USERNAME);
        DATA_SOURCE.setPassword(PASSWORD);
    }


    /**
     * 获取 数据库连接
     */
    public static Connection getConnection(){
        Connection conn=CONNECTION_HOLDER.get();
        //当没有可用的数据库连接时，就创建一个数据库连接。
        if(conn==null){
            try {
                conn= DATA_SOURCE.getConnection();
            } catch (SQLException e) {
                log.error("获得数据库连接失败");
                e.printStackTrace();
            }finally {
                CONNECTION_HOLDER.set(conn);
            }
        }
        return  conn;
    }

    public static void closeConnection(){
        Connection conn=CONNECTION_HOLDER.get();
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                log.error("数据库关闭失败",e);
                e.printStackTrace();
            }finally {
                CONNECTION_HOLDER.remove();
            }
        }
    }

    /**
     * 查询实体类
     */
    public static  <T> T queryEntity(Class<T> entityClass, String sql, Object... params){
        T entity;
        try{
            Connection conn=getConnection();
            entity=QUERY_RUNNER.query(conn,sql,new BeanHandler<T>(entityClass),params);
        }catch (SQLException e){
            throw new RuntimeException(e);
        }finally {
            closeConnection();
        }
        return entity;
    }

    /**
     * 查询列表
     */
    public static <T> List<T> queryEntityList(Class<T> entityClass, String sql, Object... params) {
        List<T> entityList;
        Connection conn = getConnection();
        try {
            entityList=QUERY_RUNNER.query(conn,sql,new BeanListHandler<T>(entityClass),params);
        } catch (SQLException e) {
            log.error("query entity list failure", e);
            throw new RuntimeException(e);
        }finally {
            closeConnection();
        }
        return entityList;
    }

    /**
     *  执行更新语句(包括update、insert、delete)
     */
    public static int executeUpdate(String sql,Object... params){
        int rows=0;
        Connection conn=getConnection();
        try {
            rows=QUERY_RUNNER.update(conn, sql, params);
        } catch (SQLException e) {
            log.error("执行修改失败");
            e.printStackTrace();
        } finally {
            closeConnection();
        }
        return rows;
    }

    /**
     * 执行SQL文件
     */
    public static void executeSqlFile(String filePath){
        InputStream is=Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
        BufferedReader reader=new BufferedReader(new InputStreamReader(is));
        try {
            String sql="";
            while ((sql=reader.readLine())!=null){
                executeUpdate(sql);
            }
        }catch (Exception e){
            log.error("读取文件："+filePath+" 行失败",e);
        }
    }
}
